﻿using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;

namespace MyEFCore
{
    public class MyModelCustomize : ModelCustomizer
    {
        public MyModelCustomize(ModelCustomizerDependencies dependencies) : base(dependencies)
        {
        }

        public override void Customize(ModelBuilder modelBuilder, DbContext context)
        {
            base.Customize(modelBuilder, context);
            foreach (var entityType in modelBuilder.Model.GetEntityTypes())
            {
                if (typeof(ISoftDelete).IsAssignableFrom(entityType.ClrType))
                {
                    var parameterExpression = Expression.Parameter(entityType.ClrType, "t");

                        var lambdaExpression = Expression.Lambda(
                            Expression.Equal(
                                Expression.Property(parameterExpression, nameof(ISoftDelete.IsDeleted)),
                                Expression.Constant(false)
                            ), parameterExpression);
                    entityType.SetQueryFilter(lambdaExpression);
                }
            }
        }
    } 
}
